<template>
  <div class="health-score">
    <div class="chart-title">
      设备健康评分
    </div>
    <div class="score-content">
      <div class="score-circle" id="healthScoreChart"></div>
    </div>
  </div>
</template>

<script>
import * as echarts from 'echarts'
import 'echarts-liquidfill'

export default {
  name: 'HealthScore',
  props: {
    healthScore: {
      type: Object,
      default: () => ({
        score: 100,
        details: [],
        status: 'normal'
      })
    }
  },
  data() {
    return {
      liquidChart: null
    }
  },
  mounted() {
    this.$nextTick(() => {
      this.initLiquidChart();
    });

    // 添加全屏变化监听
    const fullscreenHandler = () => {
      this.$nextTick(() => {
        if (this.liquidChart) {
          this.liquidChart.resize();
          const container = document.querySelector('.score-circle');
          if (container) {
            this.liquidChart.resize({
              width: 160,
              height: 160
            });
          }
          this.updateLiquidChart(this.healthScore.score);
        }
      });
    };

    document.addEventListener('fullscreenchange', fullscreenHandler);
    document.addEventListener('webkitfullscreenchange', fullscreenHandler);
    document.addEventListener('onfullscreenchange', fullscreenHandler);
    document.addEventListener('MSFullscreenChange', fullscreenHandler);

    this.fullscreenHandler = fullscreenHandler;
  },
  beforeDestroy() {
    if (this.liquidChart) {
      this.liquidChart.dispose();
      this.liquidChart = null;
    }

    // 移除监听器
    if (this.fullscreenHandler) {
      document.removeEventListener('fullscreenchange', this.fullscreenHandler);
      document.removeEventListener('webkitfullscreenchange', this.fullscreenHandler);
      document.removeEventListener('onfullscreenchange', this.fullscreenHandler);
      document.removeEventListener('MSFullscreenChange', this.fullscreenHandler);
    }
  },
  watch: {
    'healthScore.score': {
      handler(newScore) {
        this.updateLiquidChart(newScore);
      }
    }
  },
  methods: {
    initLiquidChart() {
      const chartContainer = document.querySelector('.score-circle');
      if (!chartContainer) return;

      if (!this.liquidChart) {
        this.liquidChart = echarts.init(chartContainer);
      }

      // 直接调用 updateLiquidChart 方法
      this.updateLiquidChart(this.healthScore.score);
    },
    // 获取颜色的辅助方法
    getScoreColor(score) {
      if (score >= 90) {
        // 绿色
        return {
          type: 'linear',
          x: 0, y: 0, x2: 0, y2: 1,
          colorStops: [{
            offset: 0,
            color: 'rgba(32, 184, 78, 0.8)'
          }, {
            offset: 1,
            color: 'rgba(32, 184, 78, 0.3)'
          }]
        };
      } else if (score >= 60) {
        // 黄色
        return {
          type: 'linear',
          x: 0, y: 0, x2: 0, y2: 1,
          colorStops: [{
            offset: 0,
            color: 'rgba(250, 173, 20, 0.8)'
          }, {
            offset: 1,
            color: 'rgba(250, 173, 20, 0.3)'
          }]
        };
      } else {
        // 红色
        return {
          type: 'linear',
          x: 0, y: 0, x2: 0, y2: 1,
          colorStops: [{
            offset: 0,
            color: 'rgba(255, 77, 79, 0.8)'
          }, {
            offset: 1,
            color: 'rgba(255, 77, 79, 0.3)'
          }]
        };
      }
    },

    // 获取边框颜色的辅助方法
    getBorderColor(score) {
      if (score >= 90) {
        return '#20b84e'; // 绿色
      } else if (score >= 60) {
        return '#faad14'; // 黄色
      } else {
        return '#ff4d4f'; // 红色
      }
    },

    updateLiquidChart(score = 100) {
      if (!this.liquidChart) {
        this.liquidChart = echarts.init(document.querySelector('.score-circle'));
      }

      const isFullscreen = document.fullscreenElement !== null;

      // 使用辅助方法获取颜色
      const color = this.getScoreColor(score);

      const normalizedScore = score / 100;
      const option = {
        series: [{
          type: 'liquidFill',
          data: [normalizedScore, normalizedScore * 0.9],
          radius: isFullscreen ? '90%' : '95%',
          color: [color, {
            ...color,
            colorStops: color.colorStops.map(stop => ({
              ...stop,
              color: stop.color.replace('0.8', '0.6').replace('0.3', '0.2')
            }))
          }],
          backgroundStyle: {
            color: 'transparent'
          },
          outline: {
            show: true,
            borderDistance: 2,
            itemStyle: {
              color: 'none',
              borderColor: this.getBorderColor(score),
              borderWidth: 2,
              shadowBlur: 0
            }
          },
          label: {
            show: true,
            position: ['50%', '45%'],
            formatter: () => {
              return [
                '{title|我的评分}',
                '{value|' + score + '}'
              ].join('\n');
            },
            rich: {
              title: {
                fontSize: isFullscreen ? 16 : 14,
                color: '#fff',
                padding: [0, 0, 10, 0],
                fontWeight: 'normal',
                align: 'center'
              },
              value: {
                fontSize: isFullscreen ? 42 : 36,
                color: '#fff',
                fontWeight: 'normal',
                align: 'center'
              }
            }
          },
          amplitude: 12,
          waveLength: '80%',
          phase: 0,
          period: 4000,
          direction: 'right',
          shape: 'circle',
          waveAnimation: true,
          animationEasing: 'linear',
          animationEasingUpdate: 'linear',
          animationDuration: 2000,
          animationDurationUpdate: 1000
        }]
      };

      this.liquidChart.setOption(option);
    }

  }
}
</script>

<style lang="scss" scoped>
@import './mixins/cardStyles.scss';

.health-score {
  height: calc(50% - 7.5px);
  @include card-base-style;

  .chart-title {
    @include card-title-style;
  }

  .score-content {
    flex: 1;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: flex-start;


    .score-circle {
      width: 180px;
      height: 180px;
      margin-top: 5px;
      margin-bottom: 15px;
    }

    .score-details {
      width: 100%;
      text-align: center;

      .detail-item {
        color: rgba(255, 255, 255, 0.9);
        font-size: 14px;
        margin-bottom: 5px;

        &:last-child {
          margin-bottom: 0;
        }
      }
    }
  }
}
</style>
